<?php
include($_SERVER["DOCUMENT_ROOT"] . "/bob.php");
include($_SERVER["DOCUMENT_ROOT"] . "/forum/fonctions_forum.php");
require ($_SERVER["DOCUMENT_ROOT"] . "/lib/simple_html_dom.php");
include("fonctions_messagerie.php");
$mysqli = new_mysqli($host, $user, $password, $database); //connection à la DB
$idmess = get_num($_GET['id']);
$variable_get = filter_input_array(INPUT_GET);

if (empty($_SESSION['login'])) {
    header("Location: /");
    exit();
}
$query = "SELECT user_id FROM privmsgs_thread_gens where thread_id=" . $idmess . " AND user_id=" . $_SESSION['id'];
$user = mysqli_query_with_error($mysqli, $query);
if (($user->num_rows == 0)) {
    header("Location: /");
    exit();
}
if (isset($variable_get['action'])) {
    switch ($variable_get['action']) {
        case 'archiver':
            archiver_message($mysqli, $idmess);
            header("Location: messages.php?boite=archive");
            break;
        case 'supprimer':
            supprimer_message($mysqli, $idmess);
            header("Location: messages.php");
            break;
    }
}

mysqli_query_with_error($mysqli, "UPDATE privmsgs_thread_gens SET status_recept='READ' WHERE thread_id=" . $idmess . " AND user_id=" . $_SESSION['id'] . " AND status_recept='UNREAD'");
?>


<?php
$query_thread = "SELECT * FROM privmsgs_thread as pt LEFT JOIN privmsgs_thread_gens as ptg ON pt.privmsgs_thread_id=ptg.thread_id where pt.privmsgs_thread_id=" . $idmess . " AND ptg.user_id=" . $_SESSION['id'];
$thread = mysqli_query_with_error($mysqli, $query_thread)->fetch_array();

$etat = $thread['status_recept'];
if ($etat == "UNREAD") {
    mysqli_query_with_error($mysqli, "UPDATE privmsgs_thread_gens SET status_recept='UNREAD' WHERE thread_id=" . $idmess . " AND user_id=" . $_SESSION['id']);
}

$nb_message_par_page = 10;
$retour_total = mysqli_query_with_error($mysqli, "SELECT COUNT(*) AS total FROM privmsgs WHERE thread_id=" . $idmess);
$donnees_total = $retour_total->fetch_assoc();
$total = $donnees_total['total'];

$nombreDePages = ceil($total / $nb_message_par_page);
if (isset($variable_get['page'])) {
    //echo $variable_get['page'];
    if ($variable_get['page'] == 'derniere') {
        $page = $nombreDePages;
    } else {
        $page = $variable_get['page'];
    }
} else {
    $page = $nombreDePages;
}
$pageActuelle = intval($page);

if ($pageActuelle > $nombreDePages) {
    $pageActuelle = $nombreDePages;
}
$premiereEntree = ($pageActuelle - 1) * $nb_message_par_page;

$result_messages = mysqli_query_with_error($mysqli, "SELECT * FROM privmsgs WHERE thread_id=" . $idmess . " LIMIT " . $premiereEntree . "," . $nb_message_par_page);



main_body($mysqli, get_data_propre_sortie_db($thread['thread_subject']), "bandeau;messagerie;forum");
javascript_BBcode();
display_bandeau_profil($mysqli,"message");
?>
<div id='background_corps'> </div><!-- Div contenant simplement la couleur du corps, qui vient se glisser sous le motif de bulle
                                                                                        (le vrai corp se glisse au-dessus, pour être cliquable). -->
<div id='corps'>

    <div id="contenus">
        <ul class="menu-messagerie">
            <li class="btn ombre"><a href="postmess.php">Nouveau message</a></li>
            <li class="bordure"><a href="messages.php">Boite de réception</a></li>
            <li class="bordure"><a href="messages.php?boite=envoi">Messages envoyés</a></li>
            <li><a href="messages.php?boite=archive">Messages archivés</a></li>
        </ul>
        <div class="messagerie">
            <h4 class="ombre"><?php echo get_data_propre_sortie_db($thread['thread_subject']) ?></h4>
            <ul class="actions ombre">
                <?php ?>
                <li class="btn ombre"><a href="#reponse_rapide">Répondre</a></li>
                <?php if ($etat != "ARCHIVE") { ?>
                    <li class="btn ombre"><a href="imessage.php?id=<?php echo $idmess ?>&action=archiver">Archiver</a></li>
                    <?php
                }
                ?>
                <li class="btn ombre"><a href="imessage.php?id=<?php echo $idmess ?>&action=supprimer">Supprimer</a></li>
                <li class="select droit page">                    
                    <label for="page">Aller à la page</label>

                    <select name="select" onchange="document.location.href = ('imessage.php?id=<?php echo $idmess ?>&page=' + document.getElementById('page').value)" id="page" name="select">                    
                        <?php
                        for ($i = 1; $i <= $nombreDePages; $i++) {
                            $selected = "";
                            if ($pageActuelle == $i) {
                                $selected = 'selected="selected"';
                            }
                            echo '<option value="' . $i . '" ' . $selected . '>' . $i . '</option>';
                        }
                        ?>
                    </select>

                </li>
            </ul>
            <?php
            while ($messa = $result_messages->fetch_assoc()) {
                ?>
                <div class="separator"></div>
                <div class="post">
                    <div class="profil">
                        <?php
                        $autor = get_line_in_db($mysqli, "gens", "user_id", $messa['privmsgs_from_userid']);
                        $sign = get_data_propre_sortie_db($autor['user_sig']);
                        $titre = get_data_in_db($mysqli, "titres", "titre_id", $autor['user_titre'], "titre_name");
                        $username = get_data_propre_sortie_db($autor['username']);
                        $faction = get_faction(get_data_propre_sortie_db($autor['faction']));
                        $niveau = get_data_propre_sortie_db($autor['game_level']);
                        $nb_territoire = get_data_propre_sortie_db($autor['nb_territoires']);
                        $avatar = get_data_propre_sortie_db($autor['user_avatar']);
                        $couleur = get_data_propre_sortie_db($autor['couleur']);
                        list($nb_post) = mysqli_query_with_error($mysqli, "SELECT COUNT(*) FROM forum_posts WHERE poster_id=" . $messa['privmsgs_from_userid'])->fetch_array();
                        //affichage des infos sur l'auteur
                        ?>

                        <p class="pseudo thread"><a href="/perso/profil.php?id=<?php echo $autor['user_id'] ?>"><?php echo $username ?></a></p>
                        <p class="statut"><?php echo $titre ?></p>
                        <?php echo get_avatar($avatar, $couleur) ?>
                        <p class="informations">
                            <?php echo $faction ?><br/>
                            <?php echo $nb_post . ' message' . ((get_num($nb_post) > 1) ? 's' : '') ?><br/>
                            Niveau <?php echo $niveau ?><br/>
                            <?php echo $nb_territoire . ' Territoire' . ((get_num($nb_territoire) > 1) ? 's' : '') ?>
                        </p>                        
                    </div>

                    <div id='post_<?php echo $messa['privmsgs_id'] ?>' class="message">
                        <?php
                        $datmess = datouille($messa['privmsgs_date'], true);
                        $posto = nl2br($messa['privmsgs_text']);
                        if ($messa['enable_bbcode'] == '1') {
                            $posto = traite_BBcode($posto);
                        }
                        if ($messa['enable_smilies'] == '1') {
                            $posto = traitSmiley($mysqli, $posto);
                        }
                        $verif_idef = "idefix=" . md5(session_id() . $_SESSION['id']) . "&";
                        ?>
                        <p class="infos_msg">Posté <?php echo $datmess ?>
                            <?php
//                    if ($ligne['post_edit_count'] > 0) {
//                        $datem = datouille($ligne['post_edit_time'], true);
//                        echo '- Edité ' . $ligne['post_edit_count'] . ' fois - Dernière édition ' . $datem;
//                    }
                            ?>
                        </p>
                        
                            
                        
                        <?php echo $posto ?>
                        <hr/>
                        <p class="signature"><?php echo $sign ?></p>
                        <ul class="actions">            
                            <li class="btn ombre droit"><a href="imessage.php?id=<?php echo $idmess ?>&page=derniere&citation=<?php echo $messa['privmsgs_id'] ?>&poster=<?php echo urlencode($username) ?>#reponse_rapide">Citer</a></li>
                            <li class="btn ombre bleu droit"><a href="javascript:afficher_popup('popup/signalement.php?post_id=<?php echo $messa['privmsgs_id'] ?>');">Signaler un abus</a></li>
                        </ul>
                    </div>
                </div>
                <?php
            }
            pagination_bas('imessage.php?id=' . $idmess, '&page=', $nombreDePages, $page);
            if ($page == $nombreDePages) {
                echo '<a name="reponse_rapide" />';
                echo '<h4 class="reponse">Répondre</h4>';
                javascript_BBcode();
                echo '<form id="rep_rapide" class="post ombre" action="postmess.php?action=reply&conversation=' . $idmess . '" method="POST" name="formul">';

                $query_to = "SELECT user_id FROM privmsgs_thread_gens WHERE thread_id=" . $idmess . " AND user_id!=" . $_SESSION['id'];
                $to = mysqli_query($mysqli, $query_to)->fetch_array();
                echo "<input type='hidden' name='id_destinataire' value='" . $to['user_id'] . "' />";
                echo "<input type='hidden' name='idefix' value='" . md5(session_id() . $_SESSION['id']) . "' />";

                if (isset($_GET['citation'])) {
                    $rqt_message = "SELECT privmsgs_text FROM privmsgs WHERE privmsgs_id=" . $_GET['citation'];
                    $result = mysqli_query_with_error($mysqli, $rqt_message);
                    $ligne = $result->fetch_assoc();
                    $messa = "[quote=\"" . urldecode($_GET['poster']) . "\"]" . $ligne['privmsgs_text'] . "[/quote]";
                } else {
                    $messa = "";
                }


                display_post_message(1, 1, $messa, $mysqli);


                echo '<ul class="actions">';
                echo '<li><input type="checkbox" name="auto" value="auto" name="nsmil" id="smiley_off"><label for="smiley_off">Désactiver les smileys</label></li>';
                echo '<li class="btn ombre droit"><input type="submit" value="Envoyer"></li>';
//echo '<li class="btn ombre droit"><input type="submit" value="Prévisualiser"></li>';
                echo '</ul>';

                echo '</form>';
            } else {
                echo '<ul class="actions">';
                echo '<li class="btn ombre"><a href="imessage.php?id=' . $idmess . '&page=derniere#reponse_rapide">Répondre</a></li>';
                echo '</ul>';
            }
            ?>
        </div>
    </div> <!-- fin div contenu-->
</div> <!-- fin div corps-->


<?php
show_footer();
